package com.jh3502.vivo.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.MotionEvent;

import com.jh3502.vivo.R;
import com.jh3502.vivo.utils.Utils;


/**
 * @author Harisucici
 * @date 2017/11/1 0001
 */

public class MyRecyclerView extends RecyclerView {

    private LinearLayoutManager mLayoutManager;
    private int defaultDivider = 0;
    private int divider;
    private boolean defaultTouch = true;
    private boolean touch;

    public MyRecyclerView(Context context) {
        super(context);
    }

    public MyRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        handleAttrs(context, attrs);
        mLayoutManager = new LinearLayoutManager(context);
        this.setLayoutManager(mLayoutManager);
        this.setHasFixedSize(true);
        this.addItemDecoration(new MyRecycleViewDivider(
                context, LinearLayoutManager.VERTICAL, Utils.getInstance().dp2px(context, divider),
                ContextCompat.getColor(context, R.color.gray_divider)));
    }

    private void handleAttrs(Context context, AttributeSet attrs) {
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyRecycler);
        divider = ta.getInt(R.styleable.MyRecycler_div, defaultDivider);
        touch = ta.getBoolean(R.styleable.MyRecycler_touch, defaultTouch);
        ta.recycle();
    }


    @Override
    protected void onMeasure(int widthSpec, int heightSpec) {
        super.onMeasure(widthSpec, heightSpec);

    }

    @Override
    public LinearLayoutManager getLayoutManager() {
        return mLayoutManager;
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (!touch) {
            return false;
        }
        return super.onTouchEvent(ev);
    }

    public void MoveToPosition(int n) {
        mLayoutManager.scrollToPositionWithOffset(n, 0);
        mLayoutManager.setStackFromEnd(true);
    }

    public void MoveToPosition(RecyclerView mRecyclerView, int n) {
        int firstItem = mLayoutManager.findFirstVisibleItemPosition();
        int lastItem = mLayoutManager.findLastVisibleItemPosition();
        if (n <= firstItem) {
            mRecyclerView.scrollToPosition(n);
        } else if (n <= lastItem) {
            int top = mRecyclerView.getChildAt(n - firstItem).getTop();
            mRecyclerView.scrollBy(0, top);
        } else {
            mRecyclerView.scrollToPosition(n);
        }

    }
}

